<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态棋谱</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script>
    tailwind.config = {
        theme: {
            extend: {
                colors: {
                    primary: '#8B4513',
                    secondary: '#D2B48C',
                    board: '#F5DEB3',
                    accent: '#CD5C5C',
                },
                fontFamily: {
                    inter: ['Inter', 'sans-serif'],
                },
            }
        }
    }
</script>
<style type="text/tailwindcss">
    @layer utilities {
            .chess-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
            }
            .board-grid {
                background-image: 
                  linear-gradient(to right, #8B4513 1px, transparent 1px),
                  linear-gradient(to bottom, #8B4513 1px, transparent 1px);
                background-size: 50px 100%, 100% 50px;
                background-position: 50px 0, 0 50px;
            }
            .piece-transition {
                transition: transform 0.3s ease-in-out;
            }
            .highlight {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0% {
                    box-shadow: 0 0 0 0 rgba(205, 92, 92, 0.7);
                }
                70% {
                    box-shadow: 0 0 0 10px rgba(205, 92, 92, 0);
                }
                100% {
                    box-shadow: 0 0 0 0 rgba(205, 92, 92, 0);
                }
            }
        }
    </style>
</head>

<body class="bg-gray-100 font-inter min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <header class="text-center mb-8">
            <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold text-primary mb-2">中国象棋动态棋谱</h1>
            <p class="text-gray-600 max-w-2xl mx-auto">交互式查看和学习中国象棋棋谱，支持走法记录和回放</p>
        </header>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 棋谱控制区 -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h2 class="text-xl font-semibold text-gray-800 mb-4">棋谱控制</h2>

                <div class="mb-6">
                    <label class="block text-gray-700 mb-2" for="exampleGames">选择示例棋谱</label>
                    <select id="exampleGames"
                        class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <option value="game1">仙人指路对卒底炮</option>
                        <option value="game2">中炮对屏风马</option>
                        <option value="game3">飞相对左中炮</option>
                        <option value="endGame1">楚汉争霸</option>
                    </select>
                </div>

                <div class="flex justify-between items-center mb-6">
                    <div>
                        <span class="text-gray-700 mr-2">速度控制:</span>
                        <input type="range" id="speedControl" min="1" max="10" value="5" class="w-32 accent-primary">
                    </div>
                    <span id="speedValue" class="text-sm text-gray-600">5x</span>
                </div>

                <div class="flex justify-between mb-6">
                    <button id="firstStep" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-md transition-colors">
                        <i class="fa fa-step-backward"></i> 第一步
                    </button>
                    <button id="prevStep" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-md transition-colors">
                        <i class="fa fa-backward"></i> 上一步
                    </button>
                    <button id="playPause"
                        class="px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-md transition-colors">
                        <i class="fa fa-play"></i> 播放
                    </button>
                    <button id="nextStep" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-md transition-colors">
                        <i class="fa fa-forward"></i> 下一步
                    </button>
                    <button id="lastStep" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-md transition-colors">
                        <i class="fa fa-step-forward"></i> 最后一步
                    </button>
                </div>

                <div class="mb-6">
                    <h3 class="text-lg font-medium text-gray-800 mb-2">当前步数: <span id="currentStep">0</span>/<span
                            id="totalSteps">0</span></h3>
                    <input type="range" id="stepSlider" min="0" max="0" value="0" class="w-full accent-primary">
                </div>

                <div>
                    <button id="resetBoard"
                        class="w-full py-2 bg-secondary hover:bg-secondary/90 text-primary rounded-md transition-colors font-medium">
                        重置棋盘
                    </button>
                </div>
            </div>

            <!-- 棋盘区域 -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-lg p-4 lg:p-6 relative overflow-hidden">
                    <!-- 黑方编号（上方，1-9） -->
                    <div class="w-[450px] flex justify-between mx-auto mb-6">
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">1</span>
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">2</span>
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">3</span>
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">4</span>
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">5</span>
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">6</span>
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">7</span>
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">8</span>
                        <span class="flex-1 text-center font-bold text-xl text-gray-700 select-none">9</span>
                    </div>

                    <!-- 棋盘本体 -->
                    <div id="boardContainer"
                        class="relative mx-auto aspect-square w-[450px] bg-board rounded-lg board-grid border-2 border-[#8B4513]">
                        <!-- 棋盘将在这里动态生成 -->

                        <div id="riverLineMask" style="
                                position: absolute;
                                left: 0;
                                width: 100%;
                                height: 48px;           /* 格子高度 */
                                top: 201px;             /* 第5行顶部 */
                                background: #F5DEB3;    /* 棋盘背景色 */
                                z-index: 1;             /* 文字在上面 */
                                pointer-events: none;
                             ">
                        </div>

                        <div id="riverText" style="
                                position: absolute;
                                left: 0;
                                width: 100%;
                                top: 50%;
                                transform: translateY(-50%);
                                text-align: center;
                                font-size: 2rem;
                                color: #8B4513;
                                letter-spacing: 2rem;
                                font-weight: bold;
                                opacity: 0.25;
                                pointer-events: none;
                                z-index: 1;
                                user-select: none;
                            ">
                            楚河 汉界
                        </div>

                    </div>

                    <!-- 红方编号（下方，九到一） -->
                    <div class="w-[450px] flex justify-between mx-auto mt-6">
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">九</span>
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">八</span>
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">七</span>
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">六</span>
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">五</span>
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">四</span>
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">三</span>
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">二</span>
                        <span class="flex-1 text-center font-bold text-xl text-red-700 select-none">一</span>
                    </div>

                    <div class="mt-4 bg-gray-50 rounded-lg p-4">
                        <h3 class="font-medium text-gray-800 mb-2">走法说明</h3>
                        <p id="moveDescription" class="text-gray-600">选择一个示例棋谱并点击播放按钮开始查看动态棋谱</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 走法记录区域 -->
        <div class="mt-8 bg-white rounded-xl shadow-lg p-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">走法记录</h2>
            <div id="moveHistory" class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead>
                        <tr>
                            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                步数</th>
                            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                红方</th>
                            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                黑方</th>
                        </tr>
                    </thead>
                    <tbody id="moveHistoryBody" class="bg-white divide-y divide-gray-200">
                        <!-- 走法历史将在这里动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>

        <footer class="mt-12 text-center text-gray-500 text-sm">
            <p>© 2025 中国象棋动态棋谱 | 使用 HTML, CSS 和 JavaScript 构建</p>
        </footer>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 常量定义 - 中国象棋标准棋盘（恢复最右边一列，移除最后一行）
            const BOARD_SIZE = 8; // 横向9个点（恢复标准配置）
            const BOARD_HEIGHT = 9; // 纵向9个点（移除最后一行）
            const CELL_SIZE = 50; // 每个格子的大小 (px)
            const PIECE_SIZE = 44; // 棋子大小 (px)

            // 状态变量
            let currentGame = null;
            let currentStep = 0;
            let totalSteps = 0;
            let isPlaying = false;
            let playInterval = null;
            let playSpeed = 5; // 默认速度

            // 示例棋谱数据 - 恢复最右边一列的棋子，调整棋盘高度
            const exampleGames = {
                game1: {
                    name: "仙人指路对卒底炮",
                    type: "chineseChess",
                    initialPosition: [
                        // 黑方棋子
                        { type: 'r', color: 'black', x: 0, y: 0 }, // 车
                        { type: 'n', color: 'black', x: 1, y: 0 }, // 马
                        { type: 'b', color: 'black', x: 2, y: 0 }, // 象
                        { type: 'a', color: 'black', x: 3, y: 0 }, // 士
                        { type: 'k', color: 'black', x: 4, y: 0 }, // 将
                        { type: 'a', color: 'black', x: 5, y: 0 }, // 士
                        { type: 'b', color: 'black', x: 6, y: 0 }, // 象
                        { type: 'n', color: 'black', x: 7, y: 0 }, // 马
                        { type: 'r', color: 'black', x: 8, y: 0 }, // 车（恢复最右边一列的车）
                        { type: 'c', color: 'black', x: 1, y: 2 }, // 炮
                        { type: 'c', color: 'black', x: 7, y: 2 }, // 炮（恢复到标准位置7）
                        { type: 'p', color: 'black', x: 0, y: 3 }, // 卒
                        { type: 'p', color: 'black', x: 2, y: 3 }, // 卒
                        { type: 'p', color: 'black', x: 4, y: 3 }, // 卒
                        { type: 'p', color: 'black', x: 6, y: 3 }, // 卒
                        { type: 'p', color: 'black', x: 8, y: 3 }, // 卒（恢复最右边一列的卒）

                        // 红方棋子
                        { type: 'r', color: 'red', x: 0, y: 9 }, // 车（下移两格）
                        { type: 'n', color: 'red', x: 1, y: 9 }, // 马（下移两格）
                        { type: 'b', color: 'red', x: 2, y: 9 }, // 相（下移两格）
                        { type: 'a', color: 'red', x: 3, y: 9 }, // 仕（下移两格）
                        { type: 'k', color: 'red', x: 4, y: 9 }, // 帅（下移两格）
                        { type: 'a', color: 'red', x: 5, y: 9 }, // 仕（下移两格）
                        { type: 'b', color: 'red', x: 6, y: 9 }, // 相（下移两格）
                        { type: 'n', color: 'red', x: 7, y: 9 }, // 马（下移两格）
                        { type: 'r', color: 'red', x: 8, y: 9 }, // 车（下移两格）
                        { type: 'c', color: 'red', x: 1, y: 7 }, // 炮（下移两格）
                        { type: 'c', color: 'red', x: 7, y: 7 }, // 炮（下移两格）
                        { type: 'p', color: 'red', x: 0, y: 6 }, // 兵（下移两格）
                        { type: 'p', color: 'red', x: 2, y: 6 }, // 兵（下移两格）
                        { type: 'p', color: 'red', x: 4, y: 6 }, // 兵（下移两格）
                        { type: 'p', color: 'red', x: 6, y: 6 }, // 兵（下移两格）
                        { type: 'p', color: 'red', x: 8, y: 6 }  // 兵（下移两格）
                    ],
                    moves: [
                        { from: { x: 6, y: 6 }, to: { x: 6, y: 5 }, piece: 'p', color: 'red', notation: '兵七进一' },
                        { from: { x: 2, y: 3 }, to: { x: 2, y: 4 }, piece: 'p', color: 'black', notation: '卒3进1' },
                        { from: { x: 7, y: 9 }, to: { x: 6, y: 7 }, piece: 'n', color: 'red', notation: '马八进七' },
                        { from: { x: 1, y: 0 }, to: { x: 2, y: 2 }, piece: 'n', color: 'black', notation: '马2进3' },
                        { from: { x: 8, y: 9 }, to: { x: 8, y: 8 }, piece: 'r', color: 'red', notation: '车九进一' },
                        { from: { x: 2, y: 0 }, to: { x: 4, y: 2 }, piece: 'b', color: 'black', notation: '象3进5' },
                        { from: { x: 1, y: 9 }, to: { x: 2, y: 7 }, piece: 'n', color: 'red', notation: '马二进三' },
                        { from: { x: 0, y: 0 }, to: { x: 2, y: 0 }, piece: 'r', color: 'black', notation: '车1平2' },
                        { from: { x: 8, y: 8 }, to: { x: 5, y: 8 }, piece: 'r', color: 'red', notation: '车九平六' },
                        { from: { x: 6, y: 3 }, to: { x: 6, y: 4 }, piece: 'p', color: 'black', notation: '卒7进1' }
                    ],
                    moveDescriptions: [
                        "红方兵七进一，仙人指路开局。",
                        "黑方卒3进1，应对红方。",
                        "红方马八进七，准备跳马。",
                        "黑方马2进3，发展马。",
                        "红方车九进一，出车助攻。",
                        "黑方象3进5，巩固中路。",
                        "红方马二进三，双马齐出。",
                        "黑方车1平2，出车助防。",
                        "红方车九平六，准备进攻。",
                        "黑方卒7进1，推进卒兵。"
                    ]
                },
                game2: {
                    name: "中炮对屏风马",
                    type: "chineseChess",
                    initialPosition: [], // 与game1相同
                    moves: [
                        { from: { x: 1, y: 7 }, to: { x: 4, y: 7 }, piece: 'c', color: 'red', notation: '炮二平五' },
                        { from: { x: 7, y: 0 }, to: { x: 6, y: 2 }, piece: 'n', color: 'black', notation: '马８进７' },
                        { from: { x: 1, y: 9 }, to: { x: 2, y: 7 }, piece: 'n', color: 'red', notation: '马二进三' },
                        { from: { x: 1, y: 0 }, to: { x: 2, y: 2 }, piece: 'n', color: 'black', notation: '马２进３' },
                        { from: { x: 0, y: 9 }, to: { x: 1, y: 9 }, piece: 'r', color: 'red', notation: '车一平二' },
                        { from: { x: 2, y: 0 }, to: { x: 4, y: 2 }, piece: 'b', color: 'black', notation: '象３进５' },
                        { from: { x: 1, y: 9 }, to: { x: 1, y: 3 }, piece: 'r', color: 'red', notation: '车二进六' },
                        { from: { x: 6, y: 3 }, to: { x: 6, y: 4 }, piece: 'p', color: 'black', notation: '卒７进１' },
                        { from: { x: 7, y: 9 }, to: { x: 6, y: 7 }, piece: 'n', color: 'red', notation: '马八进七' },
                        { from: { x: 2, y: 3 }, to: { x: 2, y: 4 }, piece: 'p', color: 'black', notation: '卒３进１' }
                    ],
                    moveDescriptions: [
                        '红炮二平五，形成中炮。',
                        '黑马８进７，屏风马布局。',
                        '红马二进三，发展马。',
                        '黑马２进３，双马齐出。',
                        '红车一平二，准备出车。',
                        '黑象３进５，巩固中路。',
                        '红车二进六，抢占要道。',
                        '黑卒７进１，推进卒兵。',
                        '红马八进七，双马齐出。',
                        '黑卒３进１，继续推进。'
                    ]
                },
                game3: {
                    name: "飞相对左中炮",
                    type: "chineseChess",
                    initialPosition: [], // 与game1相同
                    moves: [
                        { from: { x: 2, y: 9 }, to: { x: 4, y: 7 }, piece: 'b', color: 'red', notation: '相三进五' },
                        { from: { x: 7, y: 2 }, to: { x: 4, y: 2 }, piece: 'c', color: 'black', notation: '炮８平５' },
                        { from: { x: 1, y: 9 }, to: { x: 2, y: 7 }, piece: 'n', color: 'red', notation: '马二进三' },
                        { from: { x: 7, y: 0 }, to: { x: 6, y: 2 }, piece: 'n', color: 'black', notation: '马８进７' },
                        { from: { x: 7, y: 9 }, to: { x: 6, y: 7 }, piece: 'n', color: 'red', notation: '马八进七' },
                        { from: { x: 8, y: 0 }, to: { x: 8, y: 1 }, piece: 'r', color: 'black', notation: '车９进１' },
                        { from: { x: 0, y: 9 }, to: { x: 1, y: 9 }, piece: 'r', color: 'red', notation: '车一平二' },
                        { from: { x: 8, y: 1 }, to: { x: 7, y: 1 }, piece: 'r', color: 'black', notation: '车９平８' },
                        { from: { x: 1, y: 9 }, to: { x: 1, y: 3 }, piece: 'r', color: 'red', notation: '车二进六' },
                        { from: { x: 6, y: 3 }, to: { x: 6, y: 4 }, piece: 'p', color: 'black', notation: '卒７进１' }
                    ],
                    moveDescriptions: [
                        '红相三进五，飞相局。',
                        '黑炮８平５，左中炮。',
                        '红马二进三，发展马。',
                        '黑马８进７，屏风马布局。',
                        '红马八进七，双马齐出。',
                        '黑车９进１，准备出车。',
                        '红车一平二，准备出车。',
                        '黑车９平８，抢占要道。',
                        '红车二进六，进攻要道。',
                        '黑卒７进１，推进卒兵。'
                    ]
                },
                endGame1: {
                    name: "楚汉争霸",
                    type: "chineseChess",
                    initialPosition: [
                        { type: "r", color: "black", x: 0, y: 0 },
                        { type: "n", color: "black", x: 1, y: 0 },
                        { type: "b", color: "black", x: 2, y: 0 },
                        { type: "a", color: "black", x: 3, y: 0 },
                        { type: "k", color: "black", x: 4, y: 0 },
                        { type: "r", color: "red", x: 0, y: 9 },
                        { type: "n", color: "red", x: 1, y: 9 },
                        { type: "b", color: "red", x: 2, y: 9 },
                        { type: "k", color: "red", x: 4, y: 9 }, 
                        { type: "a", color: "red", x: 3, y: 9 }
                    ],
                    moves: [
                        { from: { x: 3, y: 9 }, to: { x: 4, y: 8 }, piece: "a", color: "red", notation: "仕 (4,1)→(5,2)" },
                        { from: { x: 1, y: 0 }, to: { x: 2, y: 2 }, piece: "n", color: "black", notation: "馬 (2,10)→(3,8)" },
                        { from: { x: 2, y: 9 }, to: { x: 4, y: 7 }, piece: "b", color: "red", notation: "相 (3,1)→(5,3)" },
                        { from: { x: 2, y: 2 }, to: { x: 3, y: 4 }, piece: "n", color: "black", notation: "馬 (3,8)→(4,6)" },
                        { from: { x: 1, y: 9 }, to: { x: 4, y: 6 }, piece: "n", color: "red", notation: "馬 (2,1)→(5,4)" },
                        { from: { x: 0, y: 0 }, to: { x: 0, y: 9 }, piece: "r", color: "black", notation: "車 (1,10)→(1,1)" },
                        { from: { x: 4, y: 6 }, to: { x: 3, y: 4 }, piece: "n", color: "red", notation: "馬 (5,4)→(4,6)" }
                    ],
                    moveDescriptions: []
                }
            };

            // 初始化棋盘容器
            const boardContainer = document.getElementById('boardContainer');
            boardContainer.style.width = `${CELL_SIZE * BOARD_SIZE}px`; // 调整棋盘宽度
            boardContainer.style.height = `${CELL_SIZE * BOARD_HEIGHT}px`; // 调整棋盘高度
            boardContainer.style.backgroundSize = `${CELL_SIZE}px ${CELL_SIZE}px`;

            // 获取DOM元素
            const exampleGamesSelect = document.getElementById('exampleGames');
            const speedControl = document.getElementById('speedControl');
            const speedValue = document.getElementById('speedValue');
            const firstStepBtn = document.getElementById('firstStep');
            const prevStepBtn = document.getElementById('prevStep');
            const playPauseBtn = document.getElementById('playPause');
            const nextStepBtn = document.getElementById('nextStep');
            const lastStepBtn = document.getElementById('lastStep');
            const currentStepEl = document.getElementById('currentStep');
            const totalStepsEl = document.getElementById('totalSteps');
            const stepSlider = document.getElementById('stepSlider');
            const resetBoardBtn = document.getElementById('resetBoard');
            const moveDescription = document.getElementById('moveDescription');
            const moveHistoryBody = document.getElementById('moveHistoryBody');

            // 棋子类型映射
            const pieceSymbols = {
                chineseChess: {
                    r: { red: '車', black: '車' },
                    n: { red: '馬', black: '馬' },
                    b: { red: '相', black: '象' },
                    a: { red: '仕', black: '士' },
                    k: { red: '帥', black: '將' },
                    c: { red: '炮', black: '炮' },
                    p: { red: '兵', black: '卒' }
                }
            };

            // 初始化事件监听器
            function initEventListeners() {
                // 示例棋谱选择变化
                exampleGamesSelect.addEventListener('change', loadSelectedGame);

                // 速度控制
                speedControl.addEventListener('input', (e) => {
                    playSpeed = parseInt(e.target.value);
                    speedValue.textContent = `${playSpeed}x`;
                    if (isPlaying) {
                        restartPlayback();
                    }
                });

                // 控制按钮
                firstStepBtn.addEventListener('click', goToFirstStep);
                prevStepBtn.addEventListener('click', goToPrevStep);
                playPauseBtn.addEventListener('click', togglePlayPause);
                nextStepBtn.addEventListener('click', goToNextStep);
                lastStepBtn.addEventListener('click', goToLastStep);
                resetBoardBtn.addEventListener('click', resetBoard);

                // 滑块控制
                stepSlider.addEventListener('input', (e) => {
                    const step = parseInt(e.target.value);
                    goToStep(step);
                });
            }

            // 加载选中的棋谱
            function loadSelectedGame() {
                const gameId = exampleGamesSelect.value;
                currentGame = exampleGames[gameId];

                // 复制初始位置数据（如果为空）
                if (currentGame.initialPosition.length === 0) {
                    currentGame.initialPosition = [...exampleGames.game1.initialPosition];
                }

                resetBoard();
                renderMoveHistory();
            }

            // 重置棋盘
            function resetBoard() {
                stopPlayback();
                currentStep = 0;
                // 只清除棋子，不清除 riverText 和编号条
                Array.from(boardContainer.children).forEach(child => {
                    if (
                        child.id !== 'riverText' &&
                        child.id !== 'riverLineMask' &&
                        child.id !== 'topLabel' &&
                        child.id !== 'bottomLabel'
                    ) {
                        boardContainer.removeChild(child);
                    }
                });

                if (!currentGame) {
                    loadSelectedGame();
                    return;
                }

                // 渲染初始棋子
                currentGame.initialPosition.forEach(piece => {
                    renderPiece(piece);
                });

                // 更新UI
                updateUI();
            }

            // 渲染棋子
            function renderPiece(piece) {
                const pieceElement = document.createElement('div');
                const symbol = pieceSymbols.chineseChess[piece.type][piece.color];
                const colorClass = piece.color === 'red' ? 'bg-red-600 text-white' : 'bg-gray-800 text-white';

                pieceElement.className = `absolute w-[${PIECE_SIZE}px] h-[${PIECE_SIZE}px] rounded-full flex items-center justify-center font-bold text-xl ${colorClass} chess-shadow piece-transition cursor-pointer`;
                // 调整棋子位置到交叉点
                pieceElement.style.left = `${piece.x * CELL_SIZE - PIECE_SIZE / 2}px`;
                pieceElement.style.top = `${piece.y * CELL_SIZE - PIECE_SIZE / 2}px`;
                pieceElement.style.zIndex = 100;
                pieceElement.dataset.id = `${piece.type}-${piece.x}-${piece.y}`;
                pieceElement.dataset.type = piece.type;
                pieceElement.dataset.color = piece.color;
                pieceElement.dataset.x = piece.x;
                pieceElement.dataset.y = piece.y;
                pieceElement.textContent = symbol;

                // 添加点击事件
                pieceElement.addEventListener('click', () => {
                    highlightPiece(pieceElement);
                });

                boardContainer.appendChild(pieceElement);
            }

            // 高亮棋子
            function highlightPiece(pieceElement) {
                // 移除所有高亮
                document.querySelectorAll('.highlight').forEach(el => {
                    el.classList.remove('highlight');
                });

                // 添加高亮
                pieceElement.classList.add('highlight');
            }

            // 更新UI
            function updateUI() {
                if (!currentGame) return;

                totalSteps = currentGame.moves.length;
                currentStepEl.textContent = currentStep;
                totalStepsEl.textContent = totalSteps;
                stepSlider.max = totalSteps;
                stepSlider.value = currentStep;

                // 更新走法说明
                if (currentStep > 0 && currentStep <= totalSteps) {
                    moveDescription.textContent = currentGame.moveDescriptions[currentStep - 1];
                } else {
                    moveDescription.textContent = "初始局面";
                }

                // 更新走法历史高亮
                document.querySelectorAll('#moveHistoryBody tr').forEach((row, index) => {
                    if (index === currentStep - 1) {
                        row.classList.add('bg-yellow-100');
                    } else {
                        row.classList.remove('bg-yellow-100');
                    }
                });

                // 更新按钮状态
                firstStepBtn.disabled = currentStep === 0;
                prevStepBtn.disabled = currentStep === 0;
                nextStepBtn.disabled = currentStep >= totalSteps;
                lastStepBtn.disabled = currentStep >= totalSteps;

                // 更新播放/暂停按钮
                if (isPlaying) {
                    playPauseBtn.innerHTML = '<i class="fa fa-pause"></i> 暂停';
                } else {
                    playPauseBtn.innerHTML = '<i class="fa fa-play"></i> 播放';
                }
            }

            // 渲染走法历史
            function renderMoveHistory() {
                if (!currentGame) return;

                moveHistoryBody.innerHTML = '';
                const moves = currentGame.moves;

                for (let i = 0; i < moves.length; i += 2) {
                    const row = document.createElement('tr');
                    row.className = 'hover:bg-gray-50 transition-colors';

                    // 步数
                    const stepCell = document.createElement('td');
                    stepCell.className = 'px-4 py-2 whitespace-nowrap text-sm font-medium text-gray-900';
                    stepCell.textContent = Math.floor(i / 2) + 1;
                    row.appendChild(stepCell);

                    // 红方走法
                    const redMoveCell = document.createElement('td');
                    redMoveCell.className = 'px-4 py-2 whitespace-nowrap text-sm text-gray-500';
                    redMoveCell.textContent = moves[i]?.notation || '';
                    row.appendChild(redMoveCell);

                    // 黑方走法
                    const blackMoveCell = document.createElement('td');
                    blackMoveCell.className = 'px-4 py-2 whitespace-nowrap text-sm text-gray-500';
                    blackMoveCell.textContent = moves[i + 1]?.notation || '';
                    row.appendChild(blackMoveCell);

                    // 添加点击事件
                    row.addEventListener('click', () => {
                        goToStep(i + 1);
                    });

                    moveHistoryBody.appendChild(row);
                }
            }

            // 执行一步走法
            function makeMove(move, animate = true) {
                // 查找要移动的棋子
                const pieceId = `${move.piece}-${move.from.x}-${move.from.y}`;
                const pieceElement = document.querySelector(`[data-id="${pieceId}"]`);

                if (pieceElement) {
                    // 检查目标位置是否有棋子（吃子）
                    const targetId = `[data-x="${move.to.x}"][data-y="${move.to.y}"]`;
                    const targetPiece = document.querySelector(targetId);

                    if (targetPiece) {
                        if (animate) {
                            targetPiece.classList.add('scale-0', 'opacity-0');
                            setTimeout(() => {
                                targetPiece.remove();
                            }, 300);
                        } else {
                            targetPiece.remove();
                        }
                    }

                    if (animate) {
                        setTimeout(() => {
                            pieceElement.style.left = `${move.to.x * CELL_SIZE - PIECE_SIZE / 2}px`;
                            pieceElement.style.top = `${move.to.y * CELL_SIZE - PIECE_SIZE / 2}px`;
                            pieceElement.dataset.id = `${move.piece}-${move.to.x}-${move.to.y}`;
                            pieceElement.dataset.x = move.to.x;
                            pieceElement.dataset.y = move.to.y;
                            highlightPiece(pieceElement);
                        }, 100);
                    } else {
                        pieceElement.style.left = `${move.to.x * CELL_SIZE - PIECE_SIZE / 2}px`;
                        pieceElement.style.top = `${move.to.y * CELL_SIZE - PIECE_SIZE / 2}px`;
                        pieceElement.dataset.id = `${move.piece}-${move.to.x}-${move.to.y}`;
                        pieceElement.dataset.x = move.to.x;
                        pieceElement.dataset.y = move.to.y;
                        // 不高亮
                    }
                }
            }

            // 前往指定步数
            function goToStep(step) {
                if (!currentGame) return;
                // 回到初始状态
                if (step === 0) {
                    resetBoard();
                    return;
                }
                // 重置棋盘到初始状态
                resetBoard();
                // 直接设置到目标步，不做动画
                for (let i = 0; i < step; i++) {
                    const move = currentGame.moves[i];
                    makeMove(move, false);
                }
                currentStep = step;
                updateUI();
            }

            // 前往第一步
            function goToFirstStep() {
                goToStep(0);
            }

            // 前往上一步
            function goToPrevStep() {
                if (currentStep > 0) {
                    goToStep(currentStep - 1);
                }
            }

            // 前往下一步
            function goToNextStep() {
                if (currentStep < currentGame.moves.length) {
                    goToStep(currentStep + 1);
                }
            }

            // 前往最后一步
            function goToLastStep() {
                if (currentGame.moves.length > 0) {
                    goToStep(currentGame.moves.length);
                }
            }

            // 开始/暂停播放
            function togglePlayPause() {
                if (isPlaying) {
                    stopPlayback();
                } else {
                    startPlayback();
                }
            }

            // 开始播放
            function startPlayback() {
                if (!currentGame || currentStep >= currentGame.moves.length) {
                    return;
                }
                isPlaying = true;
                updateUI();
                function playStep() {
                    if (!isPlaying || currentStep >= currentGame.moves.length) {
                        stopPlayback();
                        return;
                    }
                    makeMove(currentGame.moves[currentStep]);
                    currentStep++;
                    updateUI();
                    setTimeout(() => {
                        playStep();
                    }, 1000 / playSpeed);
                }
                playStep();
            }

            // 停止播放
            function stopPlayback() {
                isPlaying = false;
                if (playInterval) {
                    clearInterval(playInterval);
                    playInterval = null;
                }
                updateUI();
            }

            // 重新开始播放（用于速度变化时）
            function restartPlayback() {
                stopPlayback();
                startPlayback();
            }

            // 初始化
            initEventListeners();
            loadSelectedGame();
        });
    </script>

</body>

</html>